package org.douxiaoban.client.tab;

import java.util.ArrayList;

import org.douxiaoban.client.R;
import org.douxiaoban.client.activity.LoginActivity;
import org.douxiaoban.client.activity.NormalLoginActivity;
import org.douxiaoban.client.adapter.DouGroupNewestAdapter;
import org.douxiaoban.client.api.DouGroupApi;
import org.douxiaoban.client.util.WorkspaceView;
import org.douxiaoban.client.widget.BaseTabView;
import org.douxiaoban.client.widget.ElasticListView;
import org.douxiaoban.client.widget.ElasticListView.OnRefreshListener;
import org.douxiaoban.data.DouGroupTopicData;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.widget.Toast;

public class DouNewestTopicTab extends BaseTabView{
	
	private ElasticListView mLvNewestTopic;
	private WorkspaceView mWorkspaceView;
	private DouGroupNewestAdapter mNewestGroupAdapter;

	private static final int MSG_ERR = 0x00;
	private static final int MSG_NEWEST = 0x01;
	
	public DouNewestTopicTab(Context context){
		this(context, null);
	}
	
	public DouNewestTopicTab(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}
	
	private void init(){
		mLvNewestTopic = new ElasticListView(getContext());
		addToBodyView(mLvNewestTopic);
		mNewestGroupAdapter = new DouGroupNewestAdapter(getContext());
		mLvNewestTopic.setAdapter(mNewestGroupAdapter);
		mLvNewestTopic.setOnRefreshListener(new OnRefreshListener() {
			@Override
			public void onRefresh() {
				reqMyNewest();
			}
		});
		reqMyNewest();
		
	}
	
	private Handler mHandler = new Handler(){
		@Override
		public void handleMessage(Message msg){
			hideProgress();
			switch(msg.what){
			case MSG_NEWEST:
				ArrayList<DouGroupTopicData> datas = (ArrayList<DouGroupTopicData>)msg.obj;
				if(datas == null){
					Toast.makeText(getContext(), "cookie 过期请重新登入", Toast.LENGTH_LONG).show();
					Intent intent = new Intent();
					intent.setClass(getContext(), NormalLoginActivity.class);
					getContext().startActivity(intent);
					return;
				}
				mNewestGroupAdapter.setData(datas);
				mNewestGroupAdapter.notifyDataSetChanged();
				mLvNewestTopic.onRefreshComplete();
				break;
			case MSG_ERR:
				Toast.makeText(getContext(), getContext().getString(
					R.string.load_fail), Toast.LENGTH_LONG).show();
				break;
			}
		}
	};
	
	
	private void reqMyNewest(){
		showProgress();
		new Thread(){
			@Override
			public void run(){
				Message msg = mHandler.obtainMessage();
				try {
					ArrayList<DouGroupTopicData> datas = DouGroupApi.instance(
						getContext().getApplicationContext()).getNewestTopic();
					msg.what = MSG_NEWEST;
					msg.obj = datas;
				} catch (Exception e) {
					msg.what = MSG_ERR;
					e.printStackTrace();
				}
				mHandler.sendMessage(msg);
			}
		}.start();
	}
}